#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys
import os
import time
from MySqlPool import Mysql

import datetime
from dateutil.relativedelta import relativedelta
# get db connection

lamp_db = Mysql()




try:
	# SQL 查询语句
	sql = "select id, server_source, port_source, user_source, password_source, db_source, table_source," \
		  "server_dest, port_dest, user_dest, password_dest, db_dest, table_dest, archive_condition " \
		  "from db_archive_info"

	results = lamp_db.getAll(sql)
	datetime_now = datetime.datetime.now()
	datetime_three_month_ago = datetime_now - relativedelta(months=3)
	archive_time = datetime_three_month_ago.strftime('%Y-%m-01 00:00:00')

	# make a copy of original stdout route
	stdout_archive = sys.stdout
	# define the log file that receives your log info
	log_file = open("db_archive_exec.log", "a+")
	# redirect print output to log file
	sys.stdout = log_file

	for row in results:
		id = row['id']
		server_source = row['server_source']
		port_source = row['port_source']
		user_source = row['user_source']
		password_source = row['password_source']
		db_source = row['db_source']
		table_source = row['table_source']
		server_dest= row['server_dest']
		port_dest = row['port_dest']
		user_dest = row['user_dest']
		password_dest = row['password_dest']
		db_dest = row['db_dest']
		table_dest = row['table_dest']
		archive_condition = row['archive_condition']

		# 归档开始时间
		archive_starttime = time.strftime('%Y-%m-%d %H:%M:%S')

		# 生成pt-archive命令
		archive_cmd = "pt-archiver " \
					 "--source h='%s',P='%s',u='%s',p='%s',D='%s',t='%s' " \
					 "--dest h='%s',P='%s',u='%s',p='%s',D='%s',t='%s' " \
					 "--charset=UTF8 --where \"updatetime > '%s'\" --progress 50000 --limit 10000 --txn-size 10000 " \
					 "--bulk-insert --bulk-delete --statistics" % \
					 (server_source, port_source, user_source, password_source, db_source, table_source, \
		  			  server_dest, port_dest, user_dest, password_dest, db_dest, table_dest, \
					  archive_time)
		print(archive_cmd)



		#archive_cmd = os.popen(pt_archive)
		with os.popen(archive_cmd) as c:
		#with open("db_archive1.log", "r") as c:
			archive_log = c.read()
			print archive_log


		# 定义归档相关变量
		inserted_qty = 0
		deleted_qty = 0
		# 归档结束时间
		archive_endtime = time.strftime('%Y-%m-%d %H:%M:%S')
		print("start time %s, end time %s" %(archive_starttime,archive_endtime ))

		with open("db_archive_exec.log","r") as f:
			for line in f:
				if 'INSERT' in line:
					i = line.index(" ")
					inserted_qty = line[i+1:]
				elif 'DELETE' in line:
					i = line.index(" ")
					deleted_qty = line[i+1:]

		#判断归档是否失败
		if inserted_qty == deleted_qty:
			print("successed")
		else:
			print('inserted_qty and deleted_qty are not equal')

	# close log file
	log_file.close()
	# restore the output to initial pattern
	sys.stdout = stdout_archive

except  Exception, e:
	print str(Exception)
	print str(e)
